import React, { Component } from 'react';
import styles from './MessageItem.scss';
import { observable, action, computed } from 'mobx';
import { observer } from 'mobx-react';

import initView from '@/cross/components/View';
const View = initView(styles);
import initText from '@/cross/components/Text';
const Text = initText(styles);
import initImage from '@/cross/components/Image';
const Image = initImage(styles);
import initScrollView from '@/cross/components/ScrollView';
const ScrollView = initScrollView(styles);
import initImageBackground from '@/cross/components/ImageBackground';
const ImageBackground = initImageBackground(styles);

import { ActivityIndicator } from 'react-native';

import { qqWechatEmotionParser, emotion_title_map } from '../../utils/format';
// getTimeagoText
import { $src, px } from '@/cross/utils';
import { IMessage } from '../../types';
import imStore from '../store/im';
import { Icon } from '@/cross/components/Icon';
import { Video } from '@tarojs/components';

interface MessageItemProps {
  message: IMessage;
  onClick?: () => void;
  onLongClick?: () => void;
}

@observer
class MessageItem extends Component<MessageItemProps> {
  renderContent = (message: IMessage) => {
    const { currentPlayingAudioMsgId, playAudioMsg } = imStore;
    if (message.type === 'audio') {
      const { dur } = message.file;
      return (
        <View
          onClick={() => playAudioMsg(message)}
          className="M-flexbox-horizontal M-vertical-middle M-p-10"
        >
          <Text className="message-item__msg_text M-f-s-14 M-f-c-333 M-m-r-3">{dur}″</Text>
          <Image
            className="message-item__voice_icon"
            src={
              currentPlayingAudioMsgId === message.idServer
                ? require('../images/play_voice_right.gif')
                : require('../images/play_voice_right_no.gif')
            }
          />
        </View>
      );
    }
    if (message.type === 'image') {
      const { w, h, url, pendingUrl } = message.file;
      return (
        <View>
          <ImageBackground
            className="M-center-all"
            src={pendingUrl ? pendingUrl : $src(url)}
            style={{ width: w, height: h }}
          >
            {message.status === 'sending' && <ActivityIndicator size="small" color="#fff" />}
          </ImageBackground>
        </View>
      );
    }
    if (message.type === 'video') {
      const { w, h, url, pendingUrl } = message.file;
      return (
        <View>
          {message.status !== 'sending' && message.status !== 'fail' ? (
            <Video
              src={$src(url, { source: true })}
              autoplay={false}
              poster={$src(url, { source: true }) + '?vframe/jpg/offset/1'}
              loop={false}
              muted={false}
              style={{ width: w || px(360), height: h || px(220) }}
            />
          ) : (
            <ImageBackground
              className="M-center-all M-b-c-e"
              src={
                message.status !== 'sending' && message.status !== 'fail'
                  ? $src(url, { source: true }) + '?vframe/jpg/offset/1'
                  : require('../images/blurbg.png')
              }
              style={{ width: w || px(360), height: h || px(220) }}
            >
              {message.status === 'sending' && <ActivityIndicator size="small" color="#fff" />}
              {message.status !== 'sending' && message.status !== 'fail' && (
                <Icon name="play" theme="dark" size={60} />
              )}
            </ImageBackground>
          )}
        </View>
      );
    }
    return message.type === 'text' ? (
      <View className="M-p-10">
        <TextMsg text={message.text} />
      </View>
    ) : null;
    {
      /*
      { message.type === "custom" && message.content.type === 'namecard' && <NameCardMsg content={ message.content } userInfo={ msgUserInfo } /> }
      { message.type === "custom" && message.content.type === 'fadan' && <FadanMsg content={ message.content } /> }
      { message.type === 'geo' && <GeoMsg geo={ message.geo } /> }
    */
    }
  };

  render() {
    const { usersMap } = imStore;
    const { message, onClick, onLongClick } = this.props;
    return (
      <View className="message-item M-p-h-b-10">
        {message.flow === 'out' ? (
          <MessageItemContainer
            position="right"
            nickname="我"
            avatar={
              message.from && usersMap[message.from] && usersMap[message.from].avatar
                ? $src(usersMap[message.from].avatar)
                : require('@/cross/assets/images/default_avatar.png')
            }
            sent_time_str={message.time + ''}
            onClick={onClick}
            onLongClick={onLongClick}
          >
            {this.renderContent(message)}
          </MessageItemContainer>
        ) : (
          <MessageItemContainer
            position="left"
            nickname={message.fromNick || '没有昵称'}
            avatar={
              message.from && usersMap[message.from] && usersMap[message.from].avatar
                ? $src(usersMap[message.from].avatar)
                : require('@/cross/assets/images/default_avatar.png')
            }
            sent_time_str={message.time + ''}
            onClick={onClick}
            onLongClick={onLongClick}
          >
            {this.renderContent(message)}
          </MessageItemContainer>
        )}
      </View>
    );
  }
}

export default MessageItem;

/**
 * 容器
 */

interface MessageItemContainerProps {
  position: 'left' | 'right';
  nickname: string;
  avatar: string;
  sent_time_str?: string;
  children?: React.ReactNode;
  onClick?: () => void;
  onClickAvatar?: () => void;
  onLongClick?: () => void;
}

const MessageItemContainer = ({
  position,
  nickname,
  avatar,
  children,
  onClick,
  onClickAvatar,
  onLongClick,
}: MessageItemContainerProps) => {
  return position === 'right' ? (
    <View className="message-item__container M-flexbox-horizontal M-m-b-10">
      <View className="M-flex-item M-p-h-b-10">
        {/* <View className="M-flexbox-horizontal M-vertical-middle M-horizontal-right">
          <View>
            <Text className="M-f-c-333 M-f-s-14">{nickname}</Text>
          </View>
        </View> */}
        <View
          activeOpacity={1}
          onClick={onClick}
          onLongPress={onLongClick}
          className="M-vertical-top M-horizontal-right"
        >
          <View className="message-item__content M-m-t-10 M-center-all message-item__content__right">
            {children}
          </View>
        </View>
      </View>
      <View className="message-item__avatar__view">
        <ImageBackground className="message-item__avatar" src={avatar} />
      </View>
    </View>
  ) : (
    <View className="message-item__container M-flexbox-horizontal M-m-b-10">
      <View activeOpacity={1} onClick={onClickAvatar} className="message-item__avatar__view">
        <ImageBackground className="message-item__avatar" src={avatar} />
      </View>
      <View className="M-flex-item M-p-h-b-10">
        {/* <View className="M-flexbox-horizontal M-vertical-middle">
          <View>
            <Text className="M-f-c-333 M-f-s-14">{nickname}</Text>
          </View>
        </View> */}
        <View className="M-vertical-top">
          <View
            activeOpacity={1}
            onClick={onClick}
            onLongPress={onLongClick}
            className="message-item__content message-item__content__left M-m-t-10 M-center-all"
          >
            {children}
          </View>
        </View>
      </View>
    </View>
  );
};

/**
 * 文字消息
 */
interface TextMsgProps {
  text?: string;
}
const TextMsg = React.memo(({ text }: TextMsgProps) => {
  if (!text) return null;
  // 将微信表情代码转换成[xx]
  let showText = qqWechatEmotionParser(text, 'title');
  // 提取出[xx]分割到数组内
  const showTextArray = [];
  if (/\[[^\]]+\]/.test(showText)) {
    const emojiItems = showText.match(/\[[^\]]+\]/g);
    emojiItems &&
      emojiItems.forEach((item) => {
        const wordIndex = showText.indexOf(item);
        if (wordIndex > 0) {
          showTextArray.push(showText.substr(0, wordIndex));
          showText = showText.substr(wordIndex);
        }
        showTextArray.push(item);
        showText = showText.substr(item.length);
      });
  }
  if (showText.length > 0) {
    showTextArray.push(showText);
  }
  return (
    <View className="message-item__textmsg">
      {showTextArray.map((item, index) => {
        const id = `${item}${index}`;
        if (emotion_title_map[item]) {
          const emotion = emotion_title_map[item];
          return <Image key={id} src={emotion.img} className="message-item__textmsg__img" />;
        }
        return (
          <Text
            className="message-item__textmsg__text M-f-s-14 M-f-c-333"
            style={{ lineHeight: px(36) }}
            key={id}
          >
            {item}
          </Text>
        );
      })}
    </View>
  );
});
